package com.qifenqian.turbot.module.ui.marketing

import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.support.v7.widget.GridLayoutManager
import android.text.InputType
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.qifenqian.turbot.R
import com.qifenqian.turbot.base.BaseActivity
import com.qifenqian.turbot.config.Constant
import com.qifenqian.turbot.config.TurbotEnum
import com.qifenqian.turbot.module.adapter.itemdecoration.GridItemDecoration
import com.qifenqian.turbot.module.adapter.marketing.FreeDiscountEditAdapter
import com.qifenqian.turbot.module.contract.MarketingContract
import com.qifenqian.turbot.module.entity.response.marketing.FreeTimeDiscountDetailEntity
import com.qifenqian.turbot.module.presenter.MarketingPresenter
import com.qifenqian.turbot.util.Lcat
import com.qifenqian.turbot.util.SpUtils
import com.qifenqian.turbot.widget.CommonDialog
import com.riqthen.superedittext.SuperEditText
import kotlinx.android.synthetic.main.activity_free_discount_edit.*
import org.jetbrains.anko.toast
import java.text.SimpleDateFormat

private const val PARAM1 = "action"
const val ACTION_FREE_DISCOUNT_ADD = "action_add"
const val ACTION_FREE_DISCOUNT_EDIT = "action_edit"

/**
 * @author H
 * @createDate 2019/1/4 10:08
 * @description 添加/编辑闲时折扣
 * @see
 * @since
 */
class FreeDiscountEditActivity : BaseActivity<MarketingPresenter, MarketingContract.View>(), MarketingContract.View {

    companion object {
        fun startThis(context: Context, action: String) {
            val intent = Intent(context, FreeDiscountEditActivity::class.java)
            intent.putExtra(PARAM1, action)
            context.startActivity(intent)
        }
    }

    override fun bindLayoutId(): Int = R.layout.activity_free_discount_edit
    override fun bindPresenter(): MarketingPresenter? = MarketingPresenter(this, this)

    private var mAction: String = ACTION_DISCOUNT_ADD
    private var mDateList: MutableList<FreeTimeDiscountDetailEntity.PeriodOfLeisureTime.Date> = mutableListOf(
            FreeTimeDiscountDetailEntity.PeriodOfLeisureTime.Date("2041-01-01"),
            FreeTimeDiscountDetailEntity.PeriodOfLeisureTime.Date("2018-05-01"),
            FreeTimeDiscountDetailEntity.PeriodOfLeisureTime.Date("2011-01-01"),
            FreeTimeDiscountDetailEntity.PeriodOfLeisureTime.Date("2017-01-01"))
    private var mTimeList: MutableList<FreeTimeDiscountDetailEntity.PeriodOfLeisureTime.Time> = mutableListOf(
            FreeTimeDiscountDetailEntity.PeriodOfLeisureTime.Time("10:12", "12:55", 1.0),
            FreeTimeDiscountDetailEntity.PeriodOfLeisureTime.Time("10:12", "12:55", 1.0),
            FreeTimeDiscountDetailEntity.PeriodOfLeisureTime.Time("10:12", "12:55", 3.0))
    private var mFreeDiscountEditDateAdapter: FreeDiscountEditAdapter<FreeTimeDiscountDetailEntity.PeriodOfLeisureTime.Date>? = null
    private var mFreeDiscountEditTimeAdapter: FreeDiscountEditAdapter<FreeTimeDiscountDetailEntity.PeriodOfLeisureTime.Time>? = null
    private var mFreeTimeDiscountDetailEntity: FreeTimeDiscountDetailEntity? = null
    override fun initial() {
        mAction = intent.getStringExtra(PARAM1)
        if (mAction == ACTION_DISCOUNT_ADD) {
            tv_free_discount_edit_title.text = "添加折扣"
        } else if (mAction == ACTION_DISCOUNT_EDIT) {
            tv_free_discount_edit_title.text = "编辑折扣"
        }
        mPresenter?.getFreeTimeDiscountDetail()
        rv_free_discount_edit_date.layoutManager = GridLayoutManager(this, 3)
        rv_free_discount_edit_time.layoutManager = GridLayoutManager(this, 3)
        rv_free_discount_edit_date.addItemDecoration(GridItemDecoration(this, 16))
        rv_free_discount_edit_time.addItemDecoration(GridItemDecoration(this, 16))
        mDateList.add(FreeTimeDiscountDetailEntity.PeriodOfLeisureTime.Date("+"))
        mTimeList.add(FreeTimeDiscountDetailEntity.PeriodOfLeisureTime.Time("+", "", -1.0))
        mFreeDiscountEditDateAdapter = FreeDiscountEditAdapter(mDateList)
        mFreeDiscountEditTimeAdapter = FreeDiscountEditAdapter(mTimeList)
        rv_free_discount_edit_date.adapter = mFreeDiscountEditDateAdapter
        rv_free_discount_edit_time.adapter = mFreeDiscountEditTimeAdapter
        mFreeDiscountEditDateAdapter!!.setOnAddTimeClickListener(object : FreeDiscountEditAdapter.OnAddTimeClickListener {
            override fun onClick(position: Int) {
                showDatePickDialog()
            }
        })
        mFreeDiscountEditTimeAdapter!!.setOnAddTimeClickListener(object : FreeDiscountEditAdapter.OnAddTimeClickListener {
            override fun onClick(position: Int) {
                showTimePickDialog(true)
            }
        })
        swi_free_discount_edit_show_homepage.setOnCheckedChangeListener { buttonView, isChecked ->

        }
        btn_free_discount_edit_preview.setOnClickListener {

        }
    }

    private fun showDatePickDialog() {
        val pvTime = TimePickerBuilder(this, OnTimeSelectListener { date, v ->
            mDateList.add(mDateList.size - 1, FreeTimeDiscountDetailEntity.PeriodOfLeisureTime.Date(SimpleDateFormat("yyyy-MM-dd").format(date)))
            mFreeDiscountEditDateAdapter?.notifyDataSetChanged()
        }).setTimeSelectChangeListener {}
                .setType(booleanArrayOf(true, true, true, false, false, false))
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .build()
        val dialog = pvTime.dialog
        if (dialog != null) {
            val params = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM)
            params.leftMargin = 0
            params.rightMargin = 0
            pvTime.dialogContainerLayout.layoutParams = params
            val dialogWindow = dialog.window
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim)//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM)//改成Bottom,底部显示
            }
        }
        dialog.show()
    }

    private var mStartTime: String = ""
    private var mEndTime: String = ""
    private fun showTimePickDialog(start: Boolean) {
        val pvTime = TimePickerBuilder(this, OnTimeSelectListener { date, v ->
            if (start) {
                mStartTime = SimpleDateFormat("HH:mm").format(date)
                showTimePickDialog(false)
            } else {
                mEndTime = SimpleDateFormat("HH:mm").format(date)
                showDiscountEditDialog()
            }
        }).setTimeSelectChangeListener { Lcat.i("pvTime", "onTimeSelectChanged") }
                .setType(booleanArrayOf(false, false, false, true, true, false))
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .build()
        val dialog = pvTime.dialog
        if (dialog != null) {
            val params = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM)
            params.leftMargin = 0
            params.rightMargin = 0
            pvTime.dialogContainerLayout.layoutParams = params
            val dialogWindow = dialog.window
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim)//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM)//改成Bottom,底部显示
            }
        }
        dialog.show()
    }

    private fun showDiscountEditDialog() {
        val etDiscount = SuperEditText(this)
        etDiscount.hint = "输入折扣"
        etDiscount.textSize = 16f
        etDiscount.setBackgroundResource(com.qifenqian.turbot.R.drawable.bg_bottom_line)
        etDiscount.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
        CommonDialog(this).setTitleText("添加折扣")
                .setViews(etDiscount)
                .setCancel("取消", DialogInterface.OnClickListener { dialog, which ->
                    dialog?.dismiss()
                })
                .setOk("确定", DialogInterface.OnClickListener { dialog, which ->
                    if (etDiscount.text.toString().isBlank()) {
                        toast("请输入折扣")
                        return@OnClickListener
                    }
                    mTimeList.add(mTimeList.size - 1, FreeTimeDiscountDetailEntity.PeriodOfLeisureTime.Time(mStartTime, mEndTime, etDiscount.text.toString().toDouble()))
                    mFreeDiscountEditTimeAdapter?.notifyDataSetChanged()
                    Lcat.a("FreeDiscountEditActivity", mTimeList)
                    dialog!!.dismiss()
                })
                .setCommonCancelable(true)
                .setCommonCanceledOnTouchOutside(true)
                .show()
    }

    override fun onBackPressed() {
        super.onBackPressed()
        val freeTimeDiscountDetailRequest = FreeTimeDiscountDetailEntity(mFreeTimeDiscountDetailEntity?.id!!, listOf(),
                if (swi_free_discount_edit_show_homepage.isChecked) TurbotEnum.PRIORITY_FREE_TIME.type else mFreeTimeDiscountDetailEntity?.priority!!,
                SpUtils.getInstance().getInt(Constant.SP_KEY_RESTAURANT_ID, -1, Constant.SP_ACCOUNT))
        mDateList.removeAt(mDateList.size - 1)
        mTimeList.removeAt(mTimeList.size - 1)
        freeTimeDiscountDetailRequest.periodOfLeisureTimeList[0].dateList = mDateList
        freeTimeDiscountDetailRequest.periodOfLeisureTimeList[1].timeList = mTimeList
        Lcat.a("freeTimeDiscountDetailRequest", freeTimeDiscountDetailRequest)
        mPresenter?.saveFreeTimeDiscountDetail(freeTimeDiscountDetailRequest)
    }

    override fun getFreeTimeDiscountDetailResult(isSuccess: Boolean, code: Int, msg: String?, t: FreeTimeDiscountDetailEntity?) {
        if (isSuccess) {
            mFreeTimeDiscountDetailEntity = t
            mDateList.clear()
            mDateList.addAll(t?.periodOfLeisureTimeList!![0].dateList)
            mFreeDiscountEditDateAdapter?.notifyDataSetChanged()
            mTimeList.clear()
            mTimeList.addAll(t.periodOfLeisureTimeList[1].timeList)
            mFreeDiscountEditTimeAdapter?.notifyDataSetChanged()
        } else {
            showErrorPage(View.OnClickListener { mPresenter?.getFreeTimeDiscountDetail() }, msg)
        }
    }

    override fun saveFreeTimeDiscountDetailResult(isSuccess: Boolean, code: Int, msg: String?) {
        toast(msg!!)
    }
}
